<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, 
maximum-scale=1">
<script src="//cdn.bootcss.com/pace/1.0.2/pace.min.js"></script>
<meta name="theme-color" content="#222">

<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("http://xxxxxxx.xxx"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>


  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="unity,lua,">










<meta name="description" content="Lua 程序设计读书笔记 (一)= = 新的工作内容从前端开始。。没有IDE要学着用文本编辑器提高效率了。。狗住，我们能赢！ vs code 常用快捷键">
<meta name="keywords" content="unity,lua">
<meta property="og:type" content="article">
<meta property="og:title" content="Lua 程序设计读书笔记">
<meta property="og:url" content="http://sabistian.cn/2020/05/03/lua basic/index.html">
<meta property="og:site_name" content="Sabistian    |      Dear">
<meta property="og:description" content="Lua 程序设计读书笔记 (一)= = 新的工作内容从前端开始。。没有IDE要学着用文本编辑器提高效率了。。狗住，我们能赢！ vs code 常用快捷键">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-05-03T11:05:28.561Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Lua 程序设计读书笔记">
<meta name="twitter:description" content="Lua 程序设计读书笔记 (一)= = 新的工作内容从前端开始。。没有IDE要学着用文本编辑器提高效率了。。狗住，我们能赢！ vs code 常用快捷键">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://sabistian.cn/2020/05/03/lua basic/">





  <title>Lua 程序设计读书笔记 | Sabistian    |      Dear</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Sabistian    |      Dear</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sabistian.cn/2020/05/03/lua basic/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="邱灵雨">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/headicon.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sabistian    |      Dear">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Lua 程序设计读书笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-03T19:02:12+08:00">
                2020-05-03
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/游戏客户端/" itemprop="url" rel="index">
                    <span itemprop="name">游戏客户端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Lua-程序设计读书笔记-一"><a href="#Lua-程序设计读书笔记-一" class="headerlink" title="Lua 程序设计读书笔记 (一)"></a>Lua 程序设计读书笔记 (一)</h1><p>= = 新的工作内容从前端开始。。没有IDE要学着用文本编辑器提高效率了。。<br>狗住，我们能赢！</p>
<h2 id="vs-code-常用快捷键"><a href="#vs-code-常用快捷键" class="headerlink" title="vs code 常用快捷键"></a>vs code 常用快捷键</h2><a id="more"></a> 
<blockquote>
<ul>
<li>ctrl + p 搜索文件</li>
<li>ctrl + home/end 文件头或尾</li>
<li>shift + home/end 选择光标到行头/行尾</li>
<li>home/end 行头/行尾</li>
<li>ctrl + i 删除当前行 (自己修改)</li>
<li>ctrl + k ，ctrl + s 调出来快捷键修改页面</li>
<li>ctrl + , 文件首选项，设置字体，关闭minimap等</li>
<li>ctrl + b 当前文件对应目录结构</li>
<li>ctrl + / 注释</li>
<li>ctrl + \ 分屏</li>
<li>Alt + Up 或 Alt + Down 向上或向下移动一行</li>
<li>Shift + Alt + Up 或 Shift + Alt + Down 向上或向下复制一行 </li>
<li>Ctrl + Enter 在当前行下方插入一行  </li>
<li>Ctrl + Shift + Enter 在当前行上方插入一行</li>
<li>Shift + Alt + F 代码格式化</li>
</ul>
</blockquote>
<h2 id="Lua-语言基础"><a href="#Lua-语言基础" class="headerlink" title="Lua 语言基础"></a>Lua 语言基础</h2><h3 id="基础杂项"><a href="#基础杂项" class="headerlink" title="基础杂项"></a>基础杂项</h3><ul>
<li>and 和 or 短路求值，一种习惯写法<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">x = x <span class="keyword">or</span> v ==&gt; <span class="keyword">if</span> <span class="keyword">not</span> x <span class="keyword">then</span> x = v <span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 同理</span></span><br><span class="line">(a <span class="keyword">and</span> b) <span class="keyword">or</span> c  ==&gt; a ? b : c  <span class="comment">-- 前提是 b 不为假</span></span><br><span class="line"><span class="comment">--返回 x 与 y 较大者 </span></span><br><span class="line"><span class="built_in">max</span> = (x &gt; y) <span class="keyword">and</span> x <span class="keyword">or</span> y</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>无法确定 b 是否为真时候还是if - else 标准写法的好</p>
<ul>
<li><p>字符串连接  “..”，Lua 中的字符串是不可变的值，连接操作符只会创建一个新的字符串，不会对其原操作数进行任何修改。</p>
</li>
<li><p>操作符的优先级    </p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 应该会但是我叫不准的常识。。</span></span><br><span class="line">^</span><br><span class="line"><span class="keyword">not</span> # - (一元)</span><br><span class="line">* / %</span><br><span class="line">+ - </span><br><span class="line">..</span><br><span class="line">&lt; &gt; &lt;= &gt;= ~= ==</span><br><span class="line"><span class="keyword">and</span></span><br><span class="line"><span class="keyword">or</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>Lua 中的链表写法 虽然很少会用到 链表都用数组来实现</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">list = nul</span><br><span class="line"><span class="keyword">for</span> line <span class="keyword">in</span> <span class="built_in">io</span>.<span class="built_in">lines</span>() <span class="keyword">do</span></span><br><span class="line">    list = &#123;<span class="built_in">next</span>=list , value = line&#125;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> l = list</span><br><span class="line"><span class="keyword">while</span> l <span class="keyword">do</span> </span><br><span class="line">    <span class="built_in">print</span>(l.value)</span><br><span class="line">    l = l.<span class="built_in">next</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>可以在最后一个元素后面加一个逗号，使其不去特殊处理，也可以用分号来区分不同类型的元素。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">a = &#123;[<span class="number">1</span>] = <span class="string">"green"</span> , [<span class="number">2</span>] = <span class="string">"blue"</span> , [<span class="number">3</span>] = <span class="string">"yellow"</span>,&#125;</span><br><span class="line">&#123;x = <span class="number">10</span>,y = <span class="number">45</span> ; <span class="string">"1"</span> , <span class="string">"2"</span> , <span class="string">"3"</span>&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>允许多重赋值,并且是先对等号右边的所有元素求值，然后才执行赋值。将等号右边值的个数调整到与左边变量的个数一致，少的话赋值成nil，多余的会丢掉。<br>主要用法，交换两个元素，接收函数的多个返回值</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--交换两个元素</span></span><br><span class="line">a,b = <span class="number">10</span>,<span class="number">23</span></span><br><span class="line">a[i],a[j] = a[j],a[i]</span><br></pre></td></tr></table></figure>
</li>
<li><p>尽可能的使用局部变量，访问局部变量更快，并且局部变量可以垃圾收集器在其作用域结束的时候自动回收，一种习惯写法</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> foo = foo <span class="comment">-- 用全局变量foo 去创建并初始化一个局部变量foo</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>缩短变量的作用域可以提高可读性，并不一定要在方法的起始处声明所有的局部变量</p>
<ul>
<li><p>lua 的控制结构 if、for和while 以 end 作为结尾，repeat 以 until 作为结尾<br>lua 的if-else 写法与 <strong>mysql 语句</strong> 中的一致<br>repeat - until 相当于 do - while 保证至少执行一次，并且在循环体声明的局部变量可以用于条件测试</p>
</li>
<li><p>for 语句 两种形式，数字型 for 和 泛型</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 数字型</span></span><br><span class="line"><span class="comment">-- 表达式是一次求值，需要在循环结束后访问控制变量的值，需要将该值保存到另一个变量中，不要在循环过程中修改控制变量的值</span></span><br><span class="line"><span class="comment">-- exp3 可选，若不指定，默认以 1 递增，不设上限可以math.huge</span></span><br><span class="line"><span class="keyword">for</span> var = exp1,exp2,exp3 <span class="keyword">do</span></span><br><span class="line">    &lt;....&gt;</span><br><span class="line"><span class="keyword">end</span>    </span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i = <span class="number">1</span>,<span class="built_in">math</span>.<span class="built_in">huge</span> <span class="keyword">do</span></span><br><span class="line">    <span class="keyword">if</span> (i &gt; <span class="number">3</span>) <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">print</span>(i)</span><br><span class="line">        <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 泛型 </span></span><br><span class="line"><span class="comment">-- 在每次循环中，i被赋成索引值，v被赋予成对应于该索引的数组元素值。</span></span><br><span class="line"><span class="keyword">for</span> i , v <span class="keyword">in</span> <span class="built_in">ipairs</span>(a) <span class="keyword">do</span> <span class="built_in">print</span>(v) <span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 遍历table中的所有的key</span></span><br><span class="line"><span class="keyword">for</span> k <span class="keyword">in</span> <span class="built_in">pairs</span>(t) <span class="keyword">do</span> <span class="built_in">print</span> (k) <span class="keyword">end</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h3><p>正常函数的用法，需要将所有参数放到一对圆括号中，差别在于，当这个函数只有一个参数，并且此参数只有一个字面字符串或table 构造式，那么圆括号是可有可无的。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">print</span> <span class="string">"hello Qiu"</span></span><br><span class="line"><span class="built_in">dofile</span> <span class="string">'a.lua'</span></span><br><span class="line"></span><br><span class="line">o:foo(x)</span><br></pre></td></tr></table></figure>

<p>Lua 提供的冒号操作符使调用o.foo 时将 o 隐含地作为函数的第一个参数。</p>
<p>函数的参数与多重赋值一致，可以舍弃和用nil填充</p>
<p>多重返回值：字符串的模式匹配，返回起始，终止索引</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- eg.</span></span><br><span class="line">s, e = <span class="built_in">string</span>.<span class="built_in">find</span>(<span class="string">"hello Lua users"</span> , <span class="string">"Lua"</span>) <span class="comment">-- s = 7 , e = 9</span></span><br></pre></td></tr></table></figure>

<p>lua 函数可以返回多个返回值，将函数作为一条语句舍弃所有返回值，将函数作为表达式的一部分时，只保留第一个返回值，一个函数调用是一系列表达式中的最后一个元素(或仅有一个元素)时，获得其所有返回值。<br>多重赋值、函数调用时传入的实参列表，table 的构造式和 return 语句</p>
<p><strong>函数调用不是一系列表达式的最后一个元素，只产生一个值</strong></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo0</span><span class="params">()</span></span> <span class="keyword">end</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo1</span><span class="params">()</span></span> <span class="keyword">return</span> <span class="string">"a"</span> <span class="keyword">end</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo2</span><span class="params">()</span></span> <span class="keyword">return</span> <span class="string">"a"</span>,<span class="string">"b"</span> <span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">x,y = foo2(),<span class="number">20</span> <span class="comment">--x = "a" , y = 20</span></span><br><span class="line">x,y = foo0(),<span class="number">20</span>,<span class="number">30</span> <span class="comment">-- x = nil, y = 20</span></span><br><span class="line"><span class="comment">-- 将一个函数调用放入一对圆括号中，迫使它只返回一个结果</span></span><br><span class="line"><span class="built_in">print</span>((foo2())) <span class="comment">--&gt; a</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 变长参数</span></span><br><span class="line"><span class="comment">-- Lua 中的函数还可以接受不同数量的实参。</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span><span class="params">(...)</span></span></span><br><span class="line">    <span class="keyword">local</span> s = <span class="number">0</span></span><br><span class="line">    <span class="keyword">for</span> i , v <span class="keyword">in</span> <span class="built_in">ipairs</span>&#123;...&#125; <span class="keyword">do</span></span><br><span class="line">        s = s + v</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> s</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- ... 的行为类似与一个具有多重返回值的函数，它返回的是当前函数的所有边长参数</span></span><br><span class="line"><span class="keyword">local</span> a, b = ...</span><br></pre></td></tr></table></figure>

<p>跟踪某个特定的函数调用</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo1</span><span class="params">(...)</span></span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"calling foo:"</span>, ...)</span><br><span class="line">    <span class="keyword">return</span> foo(...)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>Lua的函数定义实际就是一条赋值语句，创建了一种类型为“函数”的值，并将这个值赋予一个变量。<br>可以将表达式“function(x)<body>end” 视为一种函数的构造式</body></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">network = &#123;</span><br><span class="line">    &#123;name = <span class="string">"grauna"</span> , IP = <span class="string">"210.26.30.64"</span>&#125;,</span><br><span class="line">    &#123;name = <span class="string">"arraial"</span> , IP = <span class="string">"210.26.30.23"</span>&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">table</span>.<span class="built_in">sort</span>(network , <span class="function"><span class="keyword">function</span><span class="params">(a,b)</span></span> <span class="keyword">return</span>(a.name &gt; b.name) <span class="keyword">end</span>)</span><br></pre></td></tr></table></figure>

<p>像可以接受另一个函数作为实参的，为“高阶函数”。 函数在Lua 中是一种“第一类值” </p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 关于导数的高阶函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">derivative</span><span class="params">(f , delta)</span></span></span><br><span class="line">    delta = delta <span class="keyword">or</span> <span class="number">1e-4</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">(x)</span></span></span><br><span class="line">            <span class="keyword">return</span> (f(x + delta) - f(x)) / delta</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>闭合函数<br>一个函数定义在另一个函数之内，并且位于内部的函数可以访问外部函数中的局部变量<br>这项特征称之为“词法域”。<br>“词法域” 和 “第一类值” 是两项极其有用的特性<br>在Lua中允许访问的原因在于函数是“第一类值”</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 可以修改某些函数 通过新的版本增加附加条件来选择调用旧的函数</span></span><br><span class="line">oldSin = <span class="built_in">math</span>.<span class="built_in">sin</span></span><br><span class="line"><span class="built_in">math</span>.<span class="built_in">sin</span> = <span class="function"><span class="keyword">function</span><span class="params">(x)</span></span></span><br><span class="line">    <span class="keyword">return</span> oldSin(x * <span class="built_in">math</span>.<span class="built_in">pi</span> / <span class="number">180</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 定义table 中的函数  感觉lua中不区分什么类型= =就是放在table里</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Lib:foo</span> <span class="params">(x , y)</span></span></span><br><span class="line">    <span class="keyword">return</span> x + y</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 程序块保证其是一个局部函数，词法域确保程序包中的其他函数可以使用这些局部函数</span></span><br></pre></td></tr></table></figure>

<p>定义递归函数的问题是说</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> fact</span><br><span class="line">fact = <span class="function"><span class="keyword">function</span> <span class="params">(n)</span></span></span><br><span class="line">    <span class="keyword">if</span> n == <span class="number">0</span> <span class="keyword">then</span></span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span></span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">return</span> n * fact(n - <span class="number">1</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- loacl fact = function(n)...直接声明加定义会出错</span></span><br><span class="line"><span class="comment">-- 因为局部变量未定义完毕就调用了</span></span><br></pre></td></tr></table></figure>

<p>Lua 的尾调用机制不会耗费任何栈空间</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">(n)</span></span></span><br><span class="line">    <span class="keyword">if</span> n &gt; <span class="number">0</span> <span class="keyword">then</span> </span><br><span class="line">        <span class="keyword">return</span> foo(n - <span class="number">1</span>) </span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>想要受益于“尾调用消除”时，务必要确定当前的调用是一条“尾调用”。<br>判断的准则就是<strong>“一个函数在调用完另一个函数之后” ，是否就无其他事情需要做了</strong></p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span><span class="params">(x)</span></span> g(x) <span class="keyword">end</span> </span><br><span class="line"><span class="comment">-- 这个就不是 类似的 </span></span><br><span class="line"><span class="keyword">return</span> g(x) + <span class="number">1</span></span><br><span class="line"><span class="keyword">return</span> x <span class="keyword">or</span> g(x)</span><br><span class="line"><span class="keyword">return</span> (g(x))</span><br><span class="line"><span class="comment">-- 尾调用消除 实质上都是完成一条goto 语句 到另一个函数，不是传统的函数调用</span></span><br></pre></td></tr></table></figure>

<h3 id="编译、执行、与错误"><a href="#编译、执行、与错误" class="headerlink" title="编译、执行、与错误"></a>编译、执行、与错误</h3><p>dofile 是一个辅助函数，loadfile 做真正核心的工作，加载并编译，讲编译结果作为一个函数返回<br>项目程序在 LuaManager 类中的Run() 方法 luaState.Dofile(“main.lua”)中执行的脚本程序</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dofile</span><span class="params">(filename)</span></span></span><br><span class="line">    <span class="keyword">local</span> f = <span class="built_in">assert</span>(<span class="built_in">loadfile</span>(filename))</span><br><span class="line">    <span class="keyword">return</span> f()</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<p>函数 loadstring 和 loadfile 类似, 不同之处它从字符串中读取代码，而非文件读取，开销较大 谨慎使用</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">f = loadstring(<span class="string">"i = i + 1"</span>) =&gt; f = <span class="function"><span class="keyword">function</span><span class="params">()</span></span> i = i + <span class="number">1</span> <span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 但第二段代码快很多，只在编译对应程序块时被编译一次。 而第一段代码却在每次调用loadstring 时都被重新编译</span></span><br><span class="line"><span class="comment">-- loadstring 在编译时不涉及词法域，上述代码并不等价</span></span><br><span class="line"></span><br><span class="line">i = <span class="number">32</span></span><br><span class="line"><span class="keyword">local</span> i = <span class="number">0</span></span><br><span class="line">f = loadstring(<span class="string">"i = i + 1; pring(i)"</span>)</span><br><span class="line">g = <span class="function"><span class="keyword">function</span><span class="params">()</span></span> i = i + <span class="number">1</span>; <span class="built_in">print</span>(i) <span class="keyword">end</span></span><br><span class="line">f()    <span class="comment">--&gt; 33</span></span><br><span class="line">g()    <span class="comment">--&gt; 1</span></span><br><span class="line"><span class="comment">-- 函数 g 操作的是局部的i，f操作的是全局的i，因为loadstring总是在全局环境中编译它的字符串</span></span><br></pre></td></tr></table></figure>

<p>Lua 提供的关于动态链接的功能都聚集在一个函数中，package.loadlib,有两个字符串参数：动态库的完整路径和一个函数名称。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> <span class="built_in">path</span> = <span class="string">"/usr/local/lib/lua/5.1/socket.so"</span></span><br><span class="line"><span class="keyword">local</span> f = <span class="built_in">package</span>.<span class="built_in">loadlib</span>(<span class="built_in">path</span>, <span class="string">"luaopen_socket"</span>)</span><br></pre></td></tr></table></figure>

<p>错误 通过调用error 函数并传入一个错误消息的参数。<br>在发生错误时不能简单地崩溃或退出。只要发生了一个错误，Lua就应该结束当前程序块并返回应用程序</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">file = <span class="built_in">assert</span>(<span class="built_in">io</span>.<span class="built_in">open</span>(name,<span class="string">"r"</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 需要在Lua中处理错误，必须使用pcall来包装需要执行的代码</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">()</span></span></span><br><span class="line">    &lt;<span class="comment">---&gt;</span></span><br><span class="line">    <span class="keyword">if</span> 未预期的条件 <span class="keyword">then</span> <span class="built_in">error</span>() <span class="keyword">end</span></span><br><span class="line">    &lt;<span class="comment">---&gt;</span></span><br><span class="line">    <span class="built_in">print</span>(a[i])</span><br><span class="line">    &lt;<span class="comment">---&gt;</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="built_in">pcall</span>(foo) <span class="keyword">then</span></span><br><span class="line">    <span class="comment">-- 在执行时没有发生错误</span></span><br><span class="line">    &lt;常规代码&gt;</span><br><span class="line"><span class="keyword">else</span></span><br><span class="line">    <span class="comment">-- foo 引发了一个错误</span></span><br><span class="line">    &lt;错误处理代码&gt;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 只要错误消息是一个字符串，Lua就会附加一些关于错误发生位置的信息</span></span><br><span class="line"><span class="keyword">local</span> <span class="built_in">status</span>,err = <span class="built_in">pcall</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span> a = <span class="string">"a"</span> + <span class="number">1</span> <span class="keyword">end</span>)</span><br><span class="line"><span class="built_in">print</span>(err)</span><br><span class="line">    <span class="comment">---&gt; stdin:1: attempt to perform arithmetic on a string value</span></span><br><span class="line"><span class="keyword">local</span> <span class="built_in">status</span>,err = <span class="built_in">pcall</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span> errpr(<span class="string">"my error"</span>) <span class="keyword">end</span>)</span><br><span class="line"><span class="built_in">print</span>(err)</span><br><span class="line">    <span class="comment">---&gt; stdin:1: my error</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- error 函数可以加个调用层级的函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span><span class="params">(str)</span></span></span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">type</span>(str) ~= <span class="string">"string"</span> <span class="keyword">then</span></span><br><span class="line">        <span class="built_in">error</span>(<span class="string">"string expected"</span> , <span class="number">2</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    &lt;<span class="comment">---&gt;</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">foo&#123;&#123;x = <span class="number">1</span>&#125;&#125;</span><br><span class="line"><span class="comment">-- pcall 函数在返回前销毁了调用栈的部分内容，想要获得有意义的调用栈，必须在pcall返回前获取该信息，Lua提供了函数xpcall</span></span><br><span class="line"><span class="comment">-- xpcall 除了接受一个需要被调用的函数，还接受第二个参数---一个错误处理函数</span></span><br></pre></td></tr></table></figure>

<h3 id="协同程序"><a href="#协同程序" class="headerlink" title="协同程序"></a>协同程序</h3><blockquote>
<ul>
<li>协同程序可以处于4种不同的状态：挂起，运行，死亡，和正常。</li>
<li>在创建时，它处于挂起状态。协同程序不会在创建它时自动执行其内容，可以通过函数status来检查协同程序的状态</li>
<li>coroutine.resume 用于启动或再次启动一个协同程序的执行，并将其状态由挂起改为运行</li>
</ul>
</blockquote>
<ul>
<li><p>Lua 中的协同程序挂起唤醒写法</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 挂起</span></span><br><span class="line">co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">(</span></span></span><br><span class="line"><span class="function"><span class="params">    for i = 1 , 10 do</span></span></span><br><span class="line"><span class="function"><span class="params">        print("co" , i)</span></span></span><br><span class="line">        coroutine.<span class="built_in">yield</span>()</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line">))</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 唤醒</span></span><br><span class="line">coroutine.<span class="built_in">resume</span>(co)</span><br><span class="line"></span><br><span class="line"><span class="comment">--可通过一对resume-yield来交换数据</span></span><br><span class="line"><span class="comment">--第一次调用resume时，传递给resume的额外参数将视为协同程序主函数的参数</span></span><br><span class="line"></span><br><span class="line">co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">(a, b, c)</span></span></span><br><span class="line">    <span class="built_in">print</span>(<span class="string">"co"</span> , a,b,c)</span><br><span class="line"><span class="keyword">end</span>)</span><br><span class="line"></span><br><span class="line">coroutine.<span class="built_in">resume</span>(co,<span class="number">1</span> ,<span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- resume 调用返回的内容中，第一个值为true则表示没有错误，后面所有的值都是对应yield传入的参数</span></span><br><span class="line">co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">(a,b)</span></span></span><br><span class="line">    coroutine.<span class="built_in">yield</span>(a + b, a - b)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line">)</span><br><span class="line"><span class="built_in">print</span>(coroutine.<span class="built_in">resume</span>(co,<span class="number">20</span>,<span class="number">10</span>)) <span class="comment">---&gt; true 30 10</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 一个协同程序结束的时候，返回值都将作为对应resume 的返回值</span></span><br><span class="line">co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span></span></span><br><span class="line"><span class="function">    <span class="title">return</span> 6 ,7</span></span><br><span class="line"><span class="function"><span class="title">end</span></span></span><br><span class="line"><span class="function">)</span></span><br><span class="line"><span class="built_in">print</span>(coroutine.<span class="built_in">resume</span>(co)) <span class="comment">--&gt; true 6,7</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>lua 提供的是一种“非对称的协同程序”，一个用于挂起，另一个用于恢复执行</p>
</li>
<li><p>例1：管道 pipe 与过滤器 filter</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">producer</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">        <span class="keyword">local</span> x = <span class="built_in">io</span>.<span class="built_in">read</span>()   <span class="comment">-- 产生新的值</span></span><br><span class="line">        send(x)               <span class="comment">-- 发送给消费者</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">consumer</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">        <span class="keyword">local</span> x = receive()   <span class="comment">-- 从生产者接收值</span></span><br><span class="line">        <span class="built_in">io</span>.<span class="built_in">write</span>(x, <span class="string">"\n"</span>)     <span class="comment">-- 消费新的值</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 协同程序匹配生产者和消费者的理想工具，一对resume - yield完成一改典型的调用者与被调用者之间的关系。</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">receive</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">local</span> <span class="built_in">status</span> , value = coroutine.<span class="built_in">resume</span>(producer)</span><br><span class="line">    <span class="keyword">return</span> value</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">send</span><span class="params">(x)</span></span></span><br><span class="line">    coroutine.<span class="built_in">yield</span>(x)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 生产者现在是一个协同和层序</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 程序通过消费者启动，当消费者需要一个新值时，唤醒生产者，生产者返回一个新值后停止运行</span></span><br><span class="line"><span class="comment">-- 消费者驱动</span></span><br><span class="line">producer = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">        <span class="keyword">local</span> x = <span class="built_in">io</span>.<span class="built_in">read</span>()</span><br><span class="line">        send(x)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 过滤器</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">filter</span><span class="params">(prod)</span></span></span><br><span class="line">    <span class="keyword">return</span> coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span></span><br><span class="line">        <span class="keyword">for</span> line = <span class="number">1</span>,<span class="built_in">math</span>.<span class="built_in">huge</span> <span class="keyword">do</span></span><br><span class="line">            <span class="keyword">local</span> x = receive(prod) <span class="comment">--获取新值</span></span><br><span class="line">            x = <span class="built_in">string</span>.<span class="built_in">format</span>(<span class="string">"%5d %s"</span> , line , x)</span><br><span class="line">            send(x)</span><br><span class="line">    )</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">consumer</span> <span class="params">(prod)</span></span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span> </span><br><span class="line">        <span class="keyword">local</span> x = receive(prod) <span class="comment">--获取新值</span></span><br><span class="line">        <span class="built_in">io</span>.<span class="built_in">write</span>(x, <span class="string">"\n"</span>)       <span class="comment">--消费新值</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">p = producer()</span><br><span class="line">f = filter(p)          ==&gt;   consumer(filter(producer))</span><br><span class="line">consumer(f) </span><br><span class="line"></span><br><span class="line"><span class="comment">-- pipe 中进程间的切换代价很高，协同程序中切换代价小的很多，writer和reader可以协作运行</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>例2：全排列</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">permgen</span><span class="params">(a,n)</span></span></span><br><span class="line">    n = n <span class="keyword">or</span> #a       <span class="comment">-- 默认n 为 a的大小</span></span><br><span class="line">    <span class="keyword">if</span> n &lt;= <span class="number">1</span> <span class="keyword">then</span></span><br><span class="line">        printResult(a)</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        <span class="keyword">for</span> i = <span class="number">1</span>,n <span class="keyword">do</span></span><br><span class="line">            <span class="comment">-- 将第 i 个元素放到数组末尾</span></span><br><span class="line">            a[n],a[i] = a[i] ,a[n]</span><br><span class="line">            <span class="comment">-- 生成其余元素的排列</span></span><br><span class="line">            permgen(a, n - <span class="number">1</span>)</span><br><span class="line">            <span class="comment">-- 恢复第 i 个元素</span></span><br><span class="line">            a[n], a[i] = a[i] , a[n]</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">printResult</span><span class="params">(a)</span></span></span><br><span class="line">    <span class="keyword">for</span> i = <span class="number">1</span>, #a <span class="keyword">do</span></span><br><span class="line">        <span class="built_in">io</span>.<span class="built_in">write</span>(a[i], <span class="string">" "</span>)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="built_in">io</span>.<span class="built_in">write</span>(<span class="string">"\n"</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 协同程序版</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">permgen</span><span class="params">(a,n)</span></span></span><br><span class="line">    n = n <span class="keyword">or</span> #a</span><br><span class="line">        <span class="keyword">if</span> n &lt;= <span class="number">1</span> <span class="keyword">then</span></span><br><span class="line">            coroutine.<span class="built_in">yield</span>(a)</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            &lt;as before&gt;</span><br><span class="line">        </span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">permutations</span><span class="params">(a)</span></span></span><br><span class="line">    <span class="keyword">local</span> co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span> permgen(a) <span class="keyword">end</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">()</span></span> <span class="comment">-- 迭代器</span></span><br><span class="line">        <span class="keyword">local</span> code, res = coroutine.<span class="built_in">resume</span>(co)</span><br><span class="line">        <span class="keyword">return</span> res</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> p <span class="keyword">in</span> permutations(<span class="string">"a"</span>,<span class="string">"b"</span>,<span class="string">"c"</span>) <span class="keyword">do</span></span><br><span class="line">    printResult(p)</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="非抢先式的-non-preemptive-多线程"><a href="#非抢先式的-non-preemptive-多线程" class="headerlink" title="非抢先式的(non-preemptive) 多线程"></a>非抢先式的(non-preemptive) 多线程</h3><p>一个线程调用一个阻塞的(blocking)操作，整个程序在操作完成前，都会停下来，非抢先的多线程用下列方法可以解决这个问题<br>一个典型的通过http 下载几个远程的文件</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">require</span> <span class="string">"socket"</span></span><br><span class="line">host = <span class="string">"www.w3.org"</span></span><br><span class="line">file = <span class="string">"/TR/REC-html32.html"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 一个TCP的连接</span></span><br><span class="line">c = <span class="built_in">assert</span>(socket.connect(host,<span class="number">80</span>))</span><br><span class="line"><span class="comment">-- 发送文件请求</span></span><br><span class="line">c:send(<span class="string">"GET"</span>..file..<span class="string">"HTTP/1.0\r\n\r\n"</span>)</span><br><span class="line"><span class="comment">-- 按1K的字节块来接收文件，并将每块写到标准输出：</span></span><br><span class="line"><span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">    <span class="keyword">local</span> s,<span class="built_in">status</span>,partial = c:receive(<span class="number">2</span>^<span class="number">10</span>)</span><br><span class="line">    <span class="built_in">io</span>.<span class="built_in">write</span>(s <span class="keyword">or</span> partial)</span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">status</span> == <span class="string">"closed"</span> <span class="keyword">then</span> </span><br><span class="line">        <span class="keyword">break</span> </span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 关闭连接</span></span><br><span class="line">c:<span class="built_in">close</span>()</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">download</span><span class="params">(host, file)</span></span></span><br><span class="line">    <span class="keyword">local</span> c = <span class="built_in">assert</span>(socket.connect(host, <span class="number">80</span>))</span><br><span class="line">    <span class="keyword">local</span> count = <span class="number">0</span> <span class="comment">-- 记录接收到字节数</span></span><br><span class="line">    c:send(<span class="string">"GET "</span>..file..<span class="string">" HTTP/1.0\r\n\r\n"</span>)</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">        <span class="keyword">local</span> s,<span class="built_in">status</span>, partial = receive(c)</span><br><span class="line">        count = count + #(s <span class="keyword">or</span> partial)</span><br><span class="line">        <span class="keyword">if</span> <span class="built_in">status</span> == <span class="string">"closed"</span> <span class="keyword">then</span> </span><br><span class="line">            <span class="keyword">break</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    c:<span class="built_in">close</span>()</span><br><span class="line">    <span class="built_in">print</span>(file,count)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">receive</span><span class="params">(connection)</span></span></span><br><span class="line">    <span class="keyword">return</span> connection:receive(<span class="number">2</span>^<span class="number">10</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="comment">-- 需要在没有足够可用数据时挂起执行。</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">receive</span><span class="params">(connection)</span></span></span><br><span class="line">    connection:settimeout(<span class="number">0</span>) <span class="comment">-- 使receive调用不会阻塞</span></span><br><span class="line">    <span class="keyword">local</span> s ,<span class="built_in">status</span>, partial = connection:receive(<span class="number">2</span> ^ <span class="number">10</span>)</span><br><span class="line">    <span class="keyword">if</span> <span class="built_in">status</span> == <span class="string">"timeout"</span> <span class="keyword">then</span></span><br><span class="line">        coroutine.<span class="built_in">yield</span>(connection)</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> s <span class="keyword">or</span> partial.<span class="built_in">status</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 一个操作返回的status 为"timeout",就表示该操作在返回时还未完成。此时，线程就会挂起执行.</span></span><br><span class="line"><span class="comment">-- 以下代码展示了调度程序及一些辅助代码.table threads 为调度程序保存这所有正在运行中的线程。</span></span><br><span class="line"><span class="comment">-- 函数get 确保每个下载任务都在一个独立的线程中执行。调度程序本身主要就是一个循环，它遍历所有的线程，</span></span><br><span class="line"><span class="comment">-- 逐个唤醒它们的执行，并且当线程完成任务时，将该线程从列表中删除。所有线程都完成运行时，停止循环</span></span><br><span class="line"></span><br><span class="line">threads = &#123;&#125; <span class="comment">-- 用于记录所有正在运行的线程</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 创建协同程序</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">get</span><span class="params">(host,file)</span></span></span><br><span class="line">    <span class="keyword">local</span> co = coroutine.<span class="built_in">create</span>(<span class="function"><span class="keyword">function</span><span class="params">()</span></span></span><br><span class="line">        download(host,file)</span><br><span class="line">    <span class="keyword">end</span>)</span><br><span class="line"><span class="comment">-- 插入记录表中</span></span><br><span class="line">    <span class="built_in">table</span>.<span class="built_in">insert</span>(threads, co)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dispatch</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">local</span> i = <span class="number">1</span></span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span> </span><br><span class="line">        <span class="keyword">if</span> threads[i] == <span class="literal">nil</span> <span class="keyword">then</span>           <span class="comment">-- 还有线程吗</span></span><br><span class="line">            <span class="keyword">if</span> threads[<span class="number">1</span>] == <span class="literal">nil</span> <span class="keyword">then</span>       <span class="comment">-- 列表是否为空</span></span><br><span class="line">                <span class="keyword">break</span>                       <span class="comment">-- 重新开始循环</span></span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">        i = <span class="number">1</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">local</span> <span class="built_in">status</span> , res = coroutine.<span class="built_in">resume</span>(threads[i])</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> res <span class="keyword">then</span></span><br><span class="line">            <span class="built_in">table</span>.<span class="built_in">remove</span>(threads, i)</span><br><span class="line">        <span class="keyword">else</span></span><br><span class="line">            i = i + <span class="number">1</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 最后主程序创建所有的线程，并调用调度程序</span></span><br><span class="line"></span><br><span class="line">host = <span class="string">"www.w3.org"</span></span><br><span class="line"></span><br><span class="line">get(host, <span class="string">"/TR/html1401/html40.txt"</span>)</span><br><span class="line">get(host, <span class="string">"/TR/2002/REC-xhtml1-20020801/xhtml.pdf"</span>)</span><br><span class="line">get(host, <span class="string">"/TR/REC-html32.html"</span>)</span><br><span class="line">get(host, <span class="string">"/TR/2000/REC-DOM-Level-2-Core-20001113/DOM2-Core.txt"</span>)</span><br><span class="line"></span><br><span class="line">dispatch()</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 除了速度有所提高外，只要有一个线程在读取数据，就不会有问题，所有线程都没有数据可读，调度程序就会执行一个"忙碌等待(Busy Wait)"</span></span><br><span class="line"><span class="comment">-- 避免这种情况，可以使用LuaSocket中的select 函数。这个函数可以用于等待一组socket的状态改变，在等待时程序陷入阻塞(block)状态。</span></span><br><span class="line"><span class="comment">-- 在当前实现中应用这个函数，调整如下</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">dispatch</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">local</span> i = <span class="number">1</span></span><br><span class="line">    <span class="keyword">local</span> connections = &#123;&#125;</span><br><span class="line">    <span class="keyword">while</span> <span class="literal">true</span> <span class="keyword">do</span></span><br><span class="line">        <span class="keyword">if</span> threads[i] == <span class="literal">nil</span> <span class="keyword">then</span> <span class="comment">-- 还有线程吗</span></span><br><span class="line">            <span class="keyword">if</span> threads[<span class="number">1</span>] == <span class="literal">nil</span> <span class="keyword">then</span> <span class="keyword">break</span> <span class="keyword">end</span></span><br><span class="line">            i = <span class="number">1</span></span><br><span class="line">            connections = &#123;&#125;</span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">local</span> <span class="built_in">status</span> ,res = coroutine.<span class="built_in">resume</span>(threads[i])</span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> res <span class="keyword">then</span></span><br><span class="line">            <span class="built_in">table</span>.<span class="built_in">remove</span>(threads, i)</span><br><span class="line">        <span class="keyword">else</span>                <span class="comment">--超时</span></span><br><span class="line">            i = i + <span class="number">1</span></span><br><span class="line">            connections(#connections + <span class="number">1</span>) = res</span><br><span class="line">            <span class="keyword">if</span> # connections == #threads <span class="keyword">then</span> <span class="comment">--所有线程都阻塞了吗</span></span><br><span class="line">                socket.<span class="built_in">select</span>(connections)</span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>

<h3 id="完整的实例-马尔可夫链算法"><a href="#完整的实例-马尔可夫链算法" class="headerlink" title="完整的实例 - 马尔可夫链算法"></a>完整的实例 - 马尔可夫链算法</h3><p>根据原始文本中n个单词的序列来确定后面的单词，生产随机的文本。本例中，n定位2，程序先读取原始文本，并创建一个table,table的创建过程为：以每两个单词为一个前缀，在table中创建一个列表，该列表记录了原始文本中所有位于该前缀之后的单词。<br>构建好这个table后，程序就利用它来生产随机文本。结果中的每个单词都来自于它在原始文本中的前缀，而具有相同前缀的单词出现在结果中的概率也与原始文本一样。最终会得到一串比较随机的文本。</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--将两个单词以空格相连，编码成一个前缀：</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">prefix</span><span class="params">(w1, w2)</span></span></span><br><span class="line">    <span class="keyword">return</span> w1..<span class="string">" "</span>..w2</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--使用字符串NOWORD("\n")来初始化一个前缀单词，并且标记文本的结尾。例如，对于原始文本：</span></span><br><span class="line">the more we try the more we <span class="keyword">do</span></span><br><span class="line"><span class="comment">-- table 如下</span></span><br><span class="line">&#123;</span><br><span class="line">    [<span class="string">"\n \n"</span>] = &#123;<span class="string">"the"</span>&#125;</span><br><span class="line">    [<span class="string">"\n the"</span>] = &#123;<span class="string">"more"</span>&#125;</span><br><span class="line">    [<span class="string">"the more"</span>] = &#123;<span class="string">"we"</span>,<span class="string">"we"</span>&#125;</span><br><span class="line">    [<span class="string">"more we"</span>] = &#123;<span class="string">"try"</span>,<span class="string">"do"</span>&#125;</span><br><span class="line">    [<span class="string">"we try"</span>] = &#123;<span class="string">"the"</span>&#125;</span><br><span class="line">    [<span class="string">"the more"</span>] = &#123;<span class="string">"more"</span>&#125;</span><br><span class="line">    [<span class="string">"we do"</span>] = &#123;<span class="string">"\n"</span>&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 程序将这个 table 保存在变量 statetab 中。若要向此table中的某个前缀列表插入一个新单词</span></span><br><span class="line"><span class="comment">-- 可以使用以下函数:</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insert</span><span class="params">(index,value)</span></span></span><br><span class="line">    <span class="keyword">local</span> list = statetab[index]</span><br><span class="line">    <span class="keyword">if</span> list = <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">        statetab[index] = &#123;value&#125;</span><br><span class="line">    <span class="keyword">else</span> </span><br><span class="line">        list[#list + <span class="number">1</span>] = value</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 用两个变量w1 和 w2 来记录最后读取的两个单词。每读取一个新单词，就将它添加到与w1 - w2相关联的列表中，然后更新w1和w2</span></span><br><span class="line"><span class="comment">-- 当创建完table后，程序便开始生产具有MAXGEN单词的文本。首先，重新初始化变量w1 和 w2。然后，对于每个前缀，程序从其对应的单词列表中随机地选出下一个单词，并打印。</span></span><br><span class="line"><span class="comment">-- 最后更新w1 和w2</span></span><br><span class="line"><span class="comment">-- 辅助函数定义</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">allwords</span><span class="params">()</span></span></span><br><span class="line">    <span class="keyword">local</span> line = <span class="built_in">io</span>.<span class="built_in">read</span>()</span><br><span class="line">    <span class="keyword">local</span> pos = <span class="number">1</span></span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span><span class="params">()</span></span></span><br><span class="line">        <span class="keyword">while</span> line <span class="keyword">do</span></span><br><span class="line">            <span class="keyword">local</span> s,e = <span class="built_in">string</span>.<span class="built_in">find</span>(line, <span class="string">"%w+"</span>, pos)</span><br><span class="line">            <span class="keyword">if</span> s <span class="keyword">then</span></span><br><span class="line">                pos = e + <span class="number">1</span></span><br><span class="line">                <span class="keyword">return</span> <span class="built_in">string</span>.<span class="built_in">sub</span>(line, s, e)</span><br><span class="line">            <span class="keyword">else</span></span><br><span class="line">                line = <span class="built_in">io</span>.<span class="built_in">read</span>()</span><br><span class="line">                pos = <span class="number">1</span></span><br><span class="line">            <span class="keyword">end</span></span><br><span class="line">        <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="keyword">return</span> <span class="literal">nil</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">prefix</span><span class="params">(w1, w2)</span></span></span><br><span class="line">    <span class="keyword">return</span> w1 .. <span class="string">" "</span> .. w2</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> statetab = &#123;&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insert</span><span class="params">(index , value)</span></span></span><br><span class="line">    <span class="keyword">local</span> list = statetab[index]</span><br><span class="line">    <span class="keyword">if</span> list == <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">        statetab[index] = &#123;value&#125;</span><br><span class="line">    <span class="keyword">else</span></span><br><span class="line">        list[#list + <span class="number">1</span>] = value</span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 主程序</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> N = <span class="number">2</span></span><br><span class="line"><span class="keyword">local</span> MAXGEN = <span class="number">10000</span></span><br><span class="line"><span class="keyword">local</span> NOWROD = <span class="string">"\n"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 构建table</span></span><br><span class="line"><span class="keyword">local</span> w1, w2 = NOWROD , NOWROD</span><br><span class="line"><span class="keyword">for</span> w <span class="keyword">in</span> allwords() <span class="keyword">do</span></span><br><span class="line">    <span class="built_in">insert</span>(prefix(w1,w2),w)</span><br><span class="line">    w1 = w2; w2 = w;</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"><span class="built_in">insert</span>(prefix(w1, w2),NOWROD)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- 生产文本</span></span><br><span class="line">w1 = NOWROD ; w2 = NOWROD <span class="comment">-- 重新初始化</span></span><br><span class="line"><span class="keyword">for</span> i = <span class="number">1</span>, MAXGEN <span class="keyword">do</span></span><br><span class="line">    <span class="keyword">local</span> list = statetab[prefix(w1,w2)]</span><br><span class="line">    <span class="comment">-- 从列表中选择一个随机项</span></span><br><span class="line">    <span class="keyword">local</span> r = <span class="built_in">math</span>.<span class="built_in">random</span>(#list)</span><br><span class="line">    <span class="keyword">local</span> nextword = list[r]</span><br><span class="line">    <span class="keyword">if</span> nextword = NOWROD <span class="keyword">then</span> </span><br><span class="line">        <span class="keyword">return</span> </span><br><span class="line">    <span class="keyword">end</span></span><br><span class="line">    <span class="built_in">io</span>.<span class="built_in">write</span>(nextword, <span class="string">" "</span>)</span><br><span class="line">    w1 = w2 ; w2 = nextword</span><br><span class="line"><span class="keyword">end</span></span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div></div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="邱灵雨 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="邱灵雨 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        
      <ul class="post-copyright">
         <li class="post-copyright-link">
          <strong>本文作者：</strong>
          <a href="/" title="欢迎访问 邱灵雨 的个人博客">邱灵雨</a>
        </li>

        <li class="post-copyright-link">
          <strong>本文链接：</strong>
          <a href="http://sabistian.cn/2020/05/03/lua basic/" title="Lua 程序设计读书笔记">http://sabistian.cn/2020/05/03/lua basic/</a>
        </li>

        <li class="post-copyright-license">
          <strong>版权声明： </strong>
          本文由 邱灵雨 原创，采用 <a href="https://creativecommons.org/licenses/by-nc-nd/4.0/deed.zh" rel="license" target="_blank">保留署名-非商业性使用-禁止演绎 4.0-国际许可协议</a> <br>转载请保留以上声明信息！
        </li>
      </ul>
<div style="text-align:center;color: #ccc;font-size:14px;">
------ 本文结束 ------</div>
      </div>
    

    <footer class="post-footer">
      
      
        <div class="post-tags">
          
            <a href="/tags/unity/" rel="tag"><i class="fa fa-tag"></i> unity</a>
          
            <a href="/tags/lua/" rel="tag"><i class="fa fa-tag"></i> lua</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/04/13/Leave/" rel="next" title="坑边闲话">
                <i class="fa fa-chevron-left"></i> 坑边闲话
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/03/ngui-mobble-fix/" rel="prev" title="Unity 中的锚点适配 - NGUI">
                Unity 中的锚点适配 - NGUI <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/headicon.png" alt="邱灵雨">
            
              <p class="site-author-name" itemprop="name">邱灵雨</p>
              <p class="site-description motion-element" itemprop="description">灵雨既零</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">20</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/sabistian" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:sebistian@163.com" target="_blank" title="Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5975979965/profile?rightmod=1&wvr=6&mod=personinfo" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/kuai-shen-l/activities" target="_blank" title="ZhiHu">
                      
                        <i class="fa fa-fw fa-globe"></i>ZhiHu</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Lua-程序设计读书笔记-一"><span class="nav-number">1.</span> <span class="nav-text">Lua 程序设计读书笔记 (一)</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#vs-code-常用快捷键"><span class="nav-number">1.1.</span> <span class="nav-text">vs code 常用快捷键</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Lua-语言基础"><span class="nav-number">1.2.</span> <span class="nav-text">Lua 语言基础</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#基础杂项"><span class="nav-number">1.2.1.</span> <span class="nav-text">基础杂项</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#函数"><span class="nav-number">1.2.2.</span> <span class="nav-text">函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#编译、执行、与错误"><span class="nav-number">1.2.3.</span> <span class="nav-text">编译、执行、与错误</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#协同程序"><span class="nav-number">1.2.4.</span> <span class="nav-text">协同程序</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#非抢先式的-non-preemptive-多线程"><span class="nav-number">1.2.5.</span> <span class="nav-text">非抢先式的(non-preemptive) 多线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#完整的实例-马尔可夫链算法"><span class="nav-number">1.2.6.</span> <span class="nav-text">完整的实例 - 马尔可夫链算法</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">邱灵雨</span>

  
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
